<template>
  <scroll-view
    class="h-screen"
    scroll-y
    :refresher-triggered="refreshing"
    refresher-enabled
    @refresherrefresh="onRefresh"
    @scrolltolower="onReachBottom"
  >
    <UniAdminPanel
      ref="panelRef"
      :fetcher="fetcher"
      @add="onAdd"
      @edit="onEdit"
      @delete="onDelete"
      @query="onQuery"
    >
      <!-- 筛选插槽 -->
      <template #filters>
        <view class="flex items-center gap-2">
          <wd-input
            v-model="filters.keyword"
            placeholder="请输入技师姓名"
            clearable
            class="flex-1"
          />
          <wd-button type="success" size="small" @click="applyFilters">
            搜索
          </wd-button>
          <wd-button size="small" plain @click="resetFilters">重置</wd-button>
        </view>
      </template>

      <!-- 列表项插槽 -->
      <template #item="{ row }">
        <view
          class="p-3 rounded-xl bg-white shadow-sm flex justify-between items-center"
        >
          <view class="flex items-center gap-3">
            <image
              v-if="row.head"
              :src="row.head || '../../static/defluat_head.png'"
              class="w-[100rpx] h-[100rpx] rounded-full"
              mode="aspectFill"
            />
            <view class="flex flex-col">
              <view class="font-medium text-base">{{ row.name }}</view>
              <view class="text-sm text-gray-500 mt-1"
                >手机号: {{ row.phone }}</view
              >
              <view class="text-sm text-gray-500 mt-1"
                >性别:
                {{
                  row.gender === 1 ? '男' : row.gender === 2 ? '女' : '未知'
                }}</view
              >
              <view class="text-sm text-gray-500 mt-1"
                >年龄: {{ row.age ?? '未知' }}</view
              >
              <view class="text-sm text-gray-500 mt-1"
                >工龄: {{ row.work_years ?? 0 }} 年</view
              >
            </view>
          </view>
          <view class="flex gap-2 ml-3">
            <wd-button size="small" type="success" plain @click="onEdit(row)">
              编辑
            </wd-button>
            <wd-button size="small" type="error" plain @click="onDelete(row)">
              删除
            </wd-button>
          </view>
        </view>
      </template>
    </UniAdminPanel>
  </scroll-view>

  <!-- 表单弹层：添加/编辑技师 -->
  <wd-overlay v-model:show="showForm" position="center" :maskClosable="false">
    <view class="wrapper">
      <view class="w-[85%] bg-white rounded-xl flex flex-col px-4 py-6">
        <view class="text-lg font-bold mb-4 text-center">{{ formTitle }}</view>

        <wd-form ref="formRef" :model="formModel">
          <wd-cell-group border>
            <wd-input
              label="姓名"
              label-width="100px"
              prop="name"
              clearable
              v-model="formModel.name"
              placeholder="请输入姓名"
              :rules="[{ required: true, message: '请填写姓名' }]"
            />
            <wd-input
              label="手机号"
              label-width="100px"
              prop="phone"
              clearable
              v-model="formModel.phone"
              placeholder="请输入手机号"
              :rules="[{ required: true, message: '请填写手机号' }]"
            />
            <wd-input
              label="密码"
              label-width="100px"
              prop="password"
              type="password"
              v-model="formModel.password"
              placeholder="请输入密码（编辑时不回显）"
              :rules="[{ required: formModel.id === 0, message: '请填写密码' }]"
            />
            <!-- 性别选择 -->
            <wd-picker
              label="性别"
              label-width="100px"
              v-model="formModel.gender"
              :columns="['男', '女', '未知']"
              placeholder="请选择性别"
            >
            </wd-picker>
            <wd-input
              label="年龄"
              label-width="100px"
              prop="age"
              type="number"
              v-model.number="formModel.age"
              placeholder="请输入年龄"
            />
            <wd-input
              label="工龄"
              label-width="100px"
              prop="work_years"
              type="number"
              v-model.number="formModel.work_years"
              placeholder="请输入工龄"
            />
          </wd-cell-group>

          <view class="flex justify-end gap-2 mt-4">
            <wd-button size="small" plain @click="showForm = false"
              >取消</wd-button
            >
            <wd-button type="primary" size="small" @click="handleSubmit"
              >保存</wd-button
            >
          </view>
        </wd-form>
      </view>
    </view>
  </wd-overlay>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import UniAdminPanel from '@/components/Table/tableComponet.vue'
import { useToast } from 'wot-design-uni'
import { masterGetAll, masterEdit, masterDelete, masterAdd } from '@/api/master'

interface Technician {
  id: number
  name: string
  phone: string
  gender?: number | null
  age?: number | null
  work_years?: number | null
  head?: string | null
  password?: string | null
}

const { success: showSuccess } = useToast()
const panelRef = ref<any>(null)
const refreshing = ref(false)

const filters = reactive({ keyword: '' })
const showForm = ref(false)
const formTitle = ref('新增技师')

const formModel = reactive<Technician & { password: string }>({
  id: 0,
  name: '',
  phone: '',
  password: '',
  gender: 0,
  age: undefined,
  work_years: undefined
})

const formRef = ref<any>(null)

// fetcher 从接口获取技师列表
const fetcher = async ({ page = 1, size = 10 }: any) => {
  const res = await masterGetAll<
    { page: number; size: number; keyword?: string },
    Technician
  >({
    page,
    size,
    keyword: filters.keyword
  })
  const { items, total } = res.data
  return { items, hasMore: page * size < total }
}

// 下拉刷新 / 底部加载
const onRefresh = async () => {
  refreshing.value = true
  await panelRef.value?.refresh()
  refreshing.value = false
}
const onReachBottom = () => panelRef.value?.loadMore()

// 搜索 / 重置
const applyFilters = () => panelRef.value?.refresh()
const resetFilters = () => {
  filters.keyword = ''
  panelRef.value?.refresh()
}

// 新增
const onAdd = () => {
  formTitle.value = '新增技师'
  Object.assign(formModel, {
    id: 0,
    name: '',
    phone: '',
    password: '',
    gender: 0,
    age: undefined,
    work_years: undefined
  })
  showForm.value = true
}

// 编辑
const onEdit = (row: Technician) => {
  formTitle.value = '编辑技师'
  Object.assign(formModel, {
    ...row,
    password: '' // 编辑时不回显
  })
  showForm.value = true
}

// 删除
const onDelete = (row: Technician) => {
  uni.showModal({
    title: '删除技师',
    content: `确定删除 "${row.name}" 吗？`,
    success: async (res: any) => {
      if (res.confirm) {
        await masterDelete<{ id: number }, any>({ id: row.id })
        uni.showToast({ title: '已删除', icon: 'none' })
        panelRef.value?.refresh()
      }
    }
  })
}

// 查询事件
const onQuery = (f: any) => {
  console.log('查询条件:', f)
}

// 提交表单
async function handleSubmit() {
  const result = await formRef.value.validate()
  if (result.valid) {
    if (formModel.id === 0) {
      await masterAdd<typeof formModel, any>({ ...formModel })
      showSuccess({ msg: '新增成功' })
    } else {
      await masterEdit<typeof formModel, any>({ ...formModel })
      showSuccess({ msg: '编辑成功' })
    }
    showForm.value = false
    panelRef.value?.refresh()
  }
}
</script>

<style scoped lang="scss">
.wrapper {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
</style>
